import requests
import os
from fake_useragent import UserAgent


class KuangStudy:
    def __init__(self) -> None:
        self.login_url = 'https://www.kuangstudy.com/login/account'
        self.sign_url = 'https://www.kuangstudy.com/u/record/qiandao'
        self.headers = {
            'user-agent': UserAgent().random
        }
        self.Phone = os.environ['KuangStudy_Phone']
        self.Password = os.environ['KuangStudy_Password']
        self.ServeCode =  os.environ['KuangStudy_ServeCode']
        self.PushPlusCode =  os.environ['KuangStudy_PushPlusCode']

        self.data = {
            'phone': self.Phone,
            'password': self.Password
        }

    def login(self):
        s = requests.session()
        s.keep_alive = False
        login_res = s.post(url=self.login_url, headers=self.headers,
                                            data=self.data).cookies.values()
        return login_res

    def sign(self):
        cookie = 'ksd_login_token=' + self.login()[1] + ";" + "ksd_login_token_id="+self.login()[
            2] + ";" + "SESSION=" + self.login()[0]
        self.headers['cookie'] = cookie
        try:
            response = requests.post(
                'https://www.kuangstudy.com/u/record/qiandao', headers=self.headers).json()

            if response['code'] == 2000 or 2001:
                if self.ServeCode:
                    serve_url = 'https://sctapi.ftqq.com/' + self.ServeCode + \
                        '.send' + '?title=' + 'KuangStudy:' + response['message']
                    serveJ = requests.post(serve_url)
                if self.PushPlusCode:
                    push_url = requests.post('http://pushplus.hxtrip.com/send?token={token}&title={title}&content={content}&template=html'.format(
                        token=self.PushPlusCode, title='KuangStudy签到成功', content=response))
            else:
                push_url = requests.post('http://pushplus.hxtrip.com/send?token={token}&title={title}&content={content}&template=html'.format(
                    token=self.PushPlusCode, title='KuangStudy签到成功', content=response))
        except Exception as e:
            if self.PushPlusCode:
                push_url = requests.post('http://pushplus.hxtrip.com/send?token={token}&title={title}&content={content}&template=html'.format(
                        token=self.PushPlusCode, title='KuangStudy签到失败', content=e))
            else:
                print(e)
                
    def run(self):
        res = KuangStudy()
        # res.login()
        res.sign()


res = KuangStudy()
res.run()
